<template>
    <div class="device">
        <el-row :gutter="20" style="width: inherit;">
            <el-col :span="6" style="width: 100%;height: 100%;">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>我的设备</span>
                    </div>
                    <div class="text item">总数: {{statistics.total}}台</div>
                    <div class="text item">正常: {{statistics.normal}}台</div>
                    <div class="text item">过期: {{statistics.expired}}台</div>
                    <div class="text item">未激活: {{statistics.invalid}}台</div>
                    <div class="text item">在线: {{statistics.onLine ? statistics.onLine.length : 0}}台</div>
                </el-card>
                <br/>
                终端设备(位置/店铺)
            <el-divider></el-divider>
            <el-row>
                <el-button size="mini" type="primary" @click="addLocation()">添加</el-button>
            </el-row>
            <br/>
                <el-table   :data="locationList"   style="width: 100%">
                    <el-table-column label="名称"  prop="name"></el-table-column>
                    <el-table-column label="地址" prop="address"></el-table-column>
                    <!-- <el-table-column label="createDate">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">
                                {{ 
                                $utils.formatDate(scope.row.deadline,"YYYY-MM-DD HH:mm:ss")
                                }}
                            </span>
                        </template>
                    </el-table-column> -->
                    <!-- <el-table-column label="状态">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">
                                {{ 
                                scope.row.status == 1 ? '正常' : (scope.row.status == 2 ? '停用' : '') 
                                }}
                            </span>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                        size="mini"
                        @click="editLocation(scope.$index)">修改</el-button>
                        <el-button
                        size="mini"
                        type="danger"
                        @click="deleteLocation(scope.$index)">删除</el-button>
                    </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        
        <el-dialog
            title="添加数据"
            :visible.sync="locationVisible"
            width="50%">
            <el-form ref="locationForm" :model="locationForm" label-width="180px">
                <el-form-item label="(店铺/位置)名称">
                    <el-input v-model="locationForm.name"></el-input>
                </el-form-item>
                <el-form-item label="(店铺/位置)区域">
                    <el-input v-model="locationForm.address"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="locationSubmit">立即创建</el-button>
                </el-form-item>
            </el-form>
            <div>
                <div id="amap-container"></div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import request from '@/utils/request'

export default {
    name: "device",
    data() {
        return {
            devicesList: [],
            searchParam: {pageNum: 1, pageSize: 100, conditions: []},
            statistics: {},
            cameraList: [],
            locationList: [],
            locationForm: {},
            locationVisible: false,
            isAdd: false,
            map: null,
        };
    },
    created() {
    },
    mounted(){
        this.getStatistics()
        this.getLocationList()
    },
    computed: {
        ...mapGetters(["name"]),
    },
    updated() {
    },
    methods: {
        getDevicesList(){
            request({
                url: '/rest/userDevices/queryList',
                method: 'post',
                data: this.searchParam
            }).then(res => {
                if(res.status){
                    this.devicesList = res.data.records
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        getStatistics(){
            request({
                url: '/rest/userDevices/statistics',
                method: 'get'
            }).then(res => {
                if(res.status){
                    this.statistics = res.data
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        getCameraList(){
            request({
                url: '/rest/camera/queryList',
                method: 'post',
                data: {pageNum: 1, pageSize: 100, conditions: [{key: "status", value: 0, method: "ge"}]}
            }).then(res => {
                if(res.status){
                    this.cameraList = res.data.records
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        getLocationList(){
            request({
                url: '/rest/location/queryList',
                method: 'post',
                data: {pageNum: 1, pageSize: 100, conditions: [{key: "status", value: 0, method: "ge"}]}
            }).then(res => {
                if(res.status){
                    this.locationList = res.data.records
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        addLocation(){
            this.isAdd = true
            this.locationVisible = true
            this.locationForm = {address: '', lng: 0, lat: 0, name: ''}
            setTimeout(() => {
                if(!this.map) this.initMap()
            },2000)
        },
        editLocation(index){
            this.isAdd = false
            this.locationVisible = true
            this.locationForm = this.locationList[index]
            setTimeout(() => {
                if(!this.map) this.initMap()
            },2000)
        },
        deleteLocation(index){
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let data = this.locationList[index]
                data.status = -1
                request({
                    url: '/rest/location/update',
                    method: 'post',
                    data: data,
                }).then(res => {
                    if(res.status){
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getLocationList()
                    }else{
                        this.$message.error(res.message);
                    }
                }).catch((e) => {
                    console.error(e)
                    this.$message.error("网络错误!");
                });
            }).catch(() => {});
        },
        locationSubmit(){
            let submitURL = this.isAdd ? '/rest/location/insert' : '/rest/location/update' 
            request({
                url: submitURL,
                method: 'post',
                data: this.locationForm,
            }).then(res => {
                if(res.status){
                    this.locationVisible = false
                    this.getLocationList()
                }else{
                    this.$message.error(res.message);
                }
            }).catch((e) => {
                console.error(e)
                this.$message.error("网络错误!");
            });
        },
        updateDomain(data){
            this.$confirm('修改可能导致部分功能无法使用, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request({
                    url: '/rest/userDevices/update',
                    method: 'post',
                    data: data
                }).then(res => {
                    if(res.status){
                        this.getDevicesList()
                    }else{
                        this.$message.error(res.message);
                    }
                }).catch((e) => {
                    console.error(e)
                    this.$message.error("网络错误!");
                });
            })
        },
        initMap(){
            this.map = new AMap.Map("amap-container", {
                resizeEnable: true
            });

            this.map.on("complete", () => {
                console.log("地图加载完成");
                this.map.setZoom(15);
            });
            
            this.map.on('click', e => {
                if(this.marker) this.map.remove(this.marker);

                this.marker = new AMap.Marker({
                    position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
                    icon: 'http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                });

                this.map.add(this.marker)
                this.locationForm.lng = e.lnglat.getLng()
                this.locationForm.lat = e.lnglat.getLat()

                if(!this.geocoder)
                    this.geocoder = new AMap.Geocoder({
                        city: "010", //城市设为北京，默认：“全国”
                        radius: 1000 //范围，默认：500
                    });

                this.geocoder.getAddress(e.lnglat, (status, result) => {
                    if (status === 'complete'&&result.regeocode) {
                        this.locationForm.address = result.regeocode.formattedAddress
                    }else{
                        log.error('根据经纬度查询地址失败')
                    }
                });
                // console.log(e)
            });

            
            this.map.plugin(['AMap.Scale'], () => {
                this.map.addControl(new AMap.Scale({}));
            });

            this.map.plugin('AMap.Geolocation', () => {
                let geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,// 是否使用高精度定位，默认：true
                        convert:true,
                        showMarker:true,
                        panToLocation:true,
                        timeout: 10000
                    });
                geolocation.getCurrentPosition();

                this.map.addControl(geolocation);

                AMap.event.addListener(geolocation, 'complete', data => {
                    console.log(data)
                })

                AMap.event.addListener(geolocation, 'error', error => {
                    console.error(error)
                })
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.device {
    height: 100%;
    width: -webkit-fill-available;

    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 18px;
    }

    .clearfix:before,
    .clearfix:after {
    display: table;
    content: "";
    }
    .clearfix:after {
    clear: both
    }
    #amap-container {    
        width: inherit;
        height: 45vh; 
    }
    .amap-icon img,
    .amap-marker-content img{
        width: 25px;
        height: 34px;
    }

    .marker {
        position: absolute;
        top: -20px;
        right: -118px;
        color: #fff;
        padding: 4px 10px;
        box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
        white-space: nowrap;
        font-size: 12px;
        font-family: "";
        background-color: #25A5F7;
        border-radius: 3px;
    }
}
</style>
